﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate;
using MvcMovie.Models;

namespace MvcMovie.Repositories
{
    public class UserRepository
    {
         private ISession session;

        public UserRepository()
        {
            this.session = MvcMovie.Util.NHibernateUtil.GetSession();
        }

        ~UserRepository()
        {
            session.Close();
        }

        public void AddUser(User user)
        {
                using (var transaction = session.BeginTransaction())
                {
                    session.Save(user);
                    transaction.Commit();
                }
        }

        public User UpdateUser(User user)
        {
            
            using (var transaction = session.BeginTransaction())
            {
                session.Merge(user);
                transaction.Commit();
            }

            return user;
        }

        public void Delete(User user)
        {
            using (var transaction = session.BeginTransaction())
            {
                session.Delete(user);
                transaction.Commit();
            }
        }

        public IEnumerable<User> GetAll()
        {
            return this.session.QueryOver<User>().List<User>();
        }

        public User GetById(int id)
        {
            var user = (User) session.Get(new User().GetType(), id);

            return user;
        }

        public User GetByUsername(string username)
        {
            var user =  this.session.QueryOver<User>().Where(u => u.Username == username).SingleOrDefault();
            if (user == null)
                throw new NullReferenceException();
            return user;
        }
    }
}
  